<?php
////////////////////////////////////////////
// 
// This is the core of the live blog.
// All the necessary functions and classes
// are defined here.
// 
// The functions are all prepend with 'lb_'
// which served as the namespace of this 
// application.
// 
////////////////////////////////////////////

// Import the BBCode Library
require_once('bbcode.php');

// This is for User side UI. This header is in the <body> protion of the page. 
function lb_gen_header($lb_mobile) {    
    // Generate header. This portion will be replaced by a isolate
    // file later, when theme support is implemented.
    $lb_name = lb_load_config('lb_main_title');
    $session_name = lb_load_config('lb_sub_title');
    $site_url = $_SERVER['PHP_SELF'];
    if($lb_mobile) {
        $lb_name_more = " (移动版)";
        $site_url .= '?s=m';
    }
    
    $html = <<<END
    <div id="header">
        <h1 id="blog_name"><a href="$site_url">{$lb_name}{$lb_name_more}</a></h1>
        <span id="blog_desc">$session_name</span>
    </div>
END;
    return $html;
}

// This is for User side UI. This footer is in the <body> protion of the page. 
function lb_gen_footer($lb_mobile) {
    // Generate footer. This portion will be replaced by a isolate
    // file later, when theme support is implemented.
    
    // Choose between Mobile and PC
    $snippit = $lb_mobile 
        ? ("<a href=\"" . $_SERVER['PHP_SELF'] . "\">普通版</a>"  . " | <a href=\"http://m.fanfou.com/ilovemac\">饭否移动版同步直播</a>")
        :("<a href=\"". $_SERVER['PHP_SELF'] . "?s=m" ."\">移动版</a>" . " | <a href=\"http://fanfou.com/ilovemac\">饭否同步直播</a>(<a href=\"http://m.fanfou.com/ilovemac\">移动版</a>)" . " | <a href=\"http://ilovemac.cn/articles/macworld-09-keynote.html\" target=\"_blank\">发表评论</a>");
    
    $html = <<<END
    <div id="footer">
        $snippit
    </div>
END;
    return $html;
}

// This is for User side UI. This body is in the <body> protion of the page. 
function lb_gen_body($is_mobile,$page) {
    // content div start
    $html = "<div id=\"content\">\n";
    //Generate Main body
    // To be implemented.
    $sid = lb_current_sid();
    $query = "SELECT pid,f_name,time,content FROM lb_users,lb_posts WHERE lb_posts.sid=$sid AND lb_posts.uid=lb_users.uid ORDER BY time DESC";
    #DEBUG echo $query;
    $results = lb_db_query("$query");
    if(mysql_num_rows ($results) != 0) {
        if ($is_mobile) {
            $entry_num = 8;
        }
        else {
            $entry_num = 20;
        }
        // Export entry counter.
        $counter = 1;
        // Total pages, the number.
        $page_total = ceil(mysql_num_rows ($results) / $entry_num);
        while(list($pid,$f_name,$time,$content) = mysql_fetch_row($results)) {
            if ($counter <= $page * $entry_num and $counter && $counter > ($page - 1) * $entry_num) {
                $content = BBCode($content);
                lb_time_str($time); // Cut the time string short.
                $html .= "<div class=\"post_entry\" id=\"entry-{$pid}\"><div class=\"post-misc\">
                                <div class=\"post-time\">$time</div>
                                <div class=\"post-author\">$f_name</div>";
                // Judge the user. It's a very very big sucurity hold.
                // I hope this won't do any bad in such a short period of time.
                if (isset($_COOKIE['author'])) {
                    $s_name = $_COOKIE['author'];
                    if(lb_user_exist($s_name)){
                        $html .= "<div class=\"post-edit\"><a href=\"lb_admin/lb_post.php?pid=$pid&action=edit\">编辑</a>/<a href=\"lb_admin/lb_post.php?pid=$pid&action=delete\">删除</a></div>";
                    }
                }
                $html .= "</div><div class=\"post-content\" ";
				if($counter == 1) {
					$html .= "id=\"first-post\"";
				}
				if ($is_mobile) {
				    // if is mobile, strip all image tags.
				    $content = eregi_replace('<img [^>]*>','(图片)',$content);
				}
				$html .= ">$content</div></div>";
                $counter++;
            }
            elseif($counter <= ($page - 1) * $entry_num){
                $counter++;
            }
            else
                break;
        }
        @lb_db_close();
    }
    else {
        lb_warn_div('info','暂时还没有任何条目哦，直播还没有开始呢。 :) ');
        lb_db_close();
    }
    $html .= lb_gen_pagebar($is_mobile, $page, $page_total);
    $html .= "</div>";
    // content div end
    return $html;
}

// Generate a pagebar
function lb_gen_pagebar($is_mobile, $page, $page_total) {
    $handler = $_SERVER['PHP_SELF'];
    $html = "<div id=\"pagebar\">";
    $prev_page = $page - 1;
    $next_page = $page + 1;
    if($is_mobile) {
        $m_request = '&s=m';
    }
    // Get a page number
    if($page > 1) {
        $html .= "<span id=\"page_up\"><a href=\"{$handler}?p={$prev_page}{$m_request}\">&lt;&lt;上一页</a></span>";
    }
    if($page < $page_total) {
        $html .= "<span id=\"page_down\"><a href=\"{$handler}?p={$next_page}{$m_request}\">下一页&gt;&gt;</a></span>";
    }
    $html .= "<div id=\"clear\">&nbsp;</div></div>";
    return $html;
}

// Generate a login form. 
function lb_login_form() {
    // Genetate a login form.
    $html =  <<<END
    <div id="login_form" class="form">
        <form action="../lb_admin/lb_login.php" method="post">
            <table>
            <tr><td>用户名：</td><td><input type="text" name="username" value="" size="20" maxlength="20"/></td></tr>
            <tr><td>密码：</td><td><input type="password" name="userpasswd" value="" size="20" maxlength="20"/></td></tr>
            <tr><td colspan="2"><input type="submit" value="登入"/><input type="hidden" value="1" name="submitted"/></td></tr>
            </table>
        </form>
    </div>
END;
return $html;
}

// Generate a logout button.
function lb_logout_form() {
    // Genetate a logout form.
    $html =  <<<END
    <div id="login_form" class="form">
        <form action="../lb_admin/lb_login.php" method="post">
            <input type="submit" value="登出"/><input type="hidden" value="1" name="logout"/>
        </form>
    </div>
END;
return $html;
}

// database query wrap functiom
function lb_db_query($query) {
    // Wrap the mysql query into one single function
    mysql_connect(DB_HOST,DB_USER,DB_PASSWD) or die("<p>数据库连接失败。<br />请检查你是否设置了错误的用户名和密码。</p>");
    mysql_select_db(DB_NAME) or die("<p>数据库打开失败。<br />请检查你是否设置了错误的数据库名。</p>");
    #DEBUG echo DB_HOST,DB_USER,DB_PASSWD,DB_NAME; #DEBUG
    #DEBUG echo $query;
    $result = mysql_query($query) or die("<p>数据库查询失败！<br />请确保你有足够的权限。</p>");
    return $result;
}
function lb_db_close($db = "") {
    // Just wrap mysql_close, to make liveblog calls more consistancy.
    // I don't know if this function could be eliminated by intergrate
    // this close call into the above query function. To avoid potential
    // bugs, just isolate this. Resolve this question later. 
    if(($db) != "") {
	@mysql_close($db);
    }
    else @mysql_close();
}

// Return an aboslute path of a file.
function lb_abs_url($file) {
    $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
    $url = rtrim($url, '/\\');
    $url .= '/' . $file;
    return $url;
}

// Generate html common code.
function lb_common_wrapper_start($title) {
    // Header is included in the wrapper.
    $html =<<<END
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>$title</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <link href="style.css" rel="stylesheet" type="text/css">
    <script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id="wrapper">
END;
    return $html;
}
function lb_common_wrapper_end() {
    $html =<<<END
</div>
</body>
</html>
END;
    return $html;
}

// Generate an infomation baner of different kind.
function lb_warn_div($type, $barner) {
    return "<div class=\"$type\">$barner</div>";
}

// Make a whole page to handle login and logout.
function lb_login_page($action) {
    // Drop an entire login form with different info barner.
    switch($action) {
        case "login":
            $title = "作者登入 :: " . lb_load_config('lb_main_title');
            break;
        case "logout":
            $title = "作者登出 :: " . lb_load_config('lb_main_title');
            $html = lb_warn_div('info', '你已经成功登出！');
            break;
        case "password":
            $title = "用户名或密码错误！ :: " . lb_load_config('lb_main_title');
            $html = lb_warn_div('warn', '用户名或密码错误！');
            break;
        default:
            // Do nothoing here.
    }
    $html = lb_common_wrapper_start($title) . $html
        . lb_login_form() . lb_common_wrapper_end();
    return $html;
}

function lb_post_form() {
    $handler = $_SERVER['PHP_SELF'];
    $html = <<<END
    <div div="post_form" class="form">
        <form action="$handler" method="post">
            <textarea name="lb_content" rows="8" cols="24"></textarea><br />
            <input type="submit" name="lb_submit" value="发表!" />
        </form>
    </div>
END;
    return $html;
}

// Liveblog posts' timestamp.
function lb_proc_time() {
    // It's quite EASY. :D 
    $time_diff = lb_load_config('lb_server_time_diff');
    list($h,$m,$s) = explode(':',substr($time_diff,1));
    $tdiff = $h * 3600 + $m * 60 + $s;
    $tdiff = substr($time_diff,0,1) . $tdiff;
    $time = time() + $tdiff - lb_load_config('lb_server_tz') * 3600 + lb_load_config('lb_place_tz') * 3600;
    $datetime = date("Y-m-d H:i:s", $time);
    return $datetime;
}

// Cut the Time String short.
// Original time string: 2008-12-22 14:57:46
// After process: 12-22 14:57 
function lb_time_str(&$time) {
    $time = substr($time, 5, 11);
}

function lb_current_uid() {
    // In future implementation, this lb_current_* function
    // will be replaced by a inquery class.
    $author = $_COOKIE['author'];
    $query = "SELECT uid FROM lb_users WHERE s_name='$author'";
    $result = lb_db_query($query);
    if ($result) {
        list($uid) = mysql_fetch_row($result);
        lb_db_close();
        return $uid;
    }
    else {
        lb_db_close();
        return false;
    }
}

function lb_current_sid() {
    // Currently simply return 1.
    // After session administration panel implemented,
    // this function will replaced by a db query.
    return 1;
}
function lb_current_utype() {
    // Currently simply return 0, means administrator.
    // Maybe this function need a parameter, like Short name.
    // After session administration panel implemented,
    // this function will replaced by a db query.
    return 0;
}

function lb_user_exist($s_name) {
    $query = "SELECT * FROM lb_users WHERE s_name='$s_name'";
    $result = lb_db_query($query);
    if(mysql_num_rows($result) >0) {
        lb_db_close();
        return true;
    }
    else {
        lb_db_close();
        return false;
    }
}

// 饭否发布函数。
function lb_fanfou($msg) {
    $user = lb_load_config('lb_ff_username');
    $pswd = lb_load_config('lb_ff_password');
    $msg = array('status' => "$msg");
    $url = "http://api.fanfou.com/statuses/update.xml";    //API URL
    $curl = curl_init();    //初始化一个curl会话
    curl_setopt($curl, CURLOPT_URL, $url);    //开始设置选项
    curl_setopt($curl,CURLOPT_VERBOSE,1);
    curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($curl,CURLOPT_USERPWD, "$user:$pswd");//设置ID/密码
    curl_setopt($curl,CURLOPT_POST,1);//设置POST方式发送
    curl_setopt($curl,CURLOPT_POSTFIELDS,$msg);//POST的字段,可以是一个关联数组
    $result = curl_exec($curl);//执行会话
    curl_close($curl);    //关闭会话
    return $result;    //返回响应信息数组
}

// This function will auto split long msgs, so that no info will miss.
// This function calls the lb_fanfou() to send msg.
function lb_fanfou_autosplit($msg) {
    $msg = html_entity_decode($msg);
    $msg = strip_tags(BBCode($msg));
    $ff_prefix = lb_load_config('lb_ff_prefix');
    if (strlen(trim($msg)) == 0) {
        // if no char left, just return.    
        return;
    }
    while(mb_strlen($msg,'UTF-8') > 140) {
        $msg_part = mb_substr($msg, mb_strlen($msg,'UTF-8') - 140 + mb_strlen($ff_prefix,'UTF-8'), 140 - mb_strlen($ff_prefix,'UTF-8'),'UTF-8');
        // Prepend a Prefix to all the Fanfou messages.
        lb_fanfou($ff_prefix . $msg_part);
        $msg = mb_substr($msg, 0, mb_strlen($msg,'UTF-8') - 140 + mb_strlen($ff_prefix,'UTF-8'),'UTF-8');
    }
    lb_fanfou($ff_prefix . $msg);
}

// Get a list of users.
// Future implementation, Previledge control will be added to lb_user_admin.php
// So Simply genetate a form.
// As long as the user is logged in, so trust him/her.
// Maybe I will add some password auth. :)
function lb_user_list($current_uid) {
    // Generate the table
    // Now only the user him/her-self can modify his/her personal info.
    // For now, it's OK. :)
    $handler = $_SERVER['PHP_SELF'];
    $html = <<<END
    <div class="info_table">
        <h3>用户信息</h3>
        <table>
        <tr><td>ID</td><td>登录名</td><td>全名</td><td>Email</td><td>用户类型</td><td>编辑</td></tr>
END;
    // Genetare table rows.
    $query = "SELECT uid,s_name,f_name,email,type FROM lb_users";
    $result = lb_db_query($query);
    // User Type id -> String.
    // Temperarily, just two kind of users.
    // Yes, actually Author is not implemented yet. :P
    $id_str = array (
        '0' => "管理员",
        '1' => "作者"
    );
    
    // Because, at least one user exist, so just list the table.
    while(list($uid,$s_name,$f_name,$email,$type) = mysql_fetch_row($result)) {
        if($uid == 1) {$type="站长";}
        else $type = strtr($type, $id_str);
        // Set a css class here. Let Javascript to do the warning.
        if($uid != $current_uid) {
            $deluser_code = "<a href=\"" . $handler . "?duid=" . $uid . "\" class=\"del_warn\">删除?</a>";
        }
        else {
            $deluser_code = "<a href=\"#userinfo_change_form\" class=\"del_warn\">修改?</a>";
        }
        $html .= "<tr><td>$uid</td><td>$s_name</td><td>$f_name</td><td>$email</td><td>$type</td><td>$deluser_code</td></tr>";
    }
    lb_db_close();
    $html .= <<<END
        </table>
    </div>
END;
    return $html;
}

// Gen a user add form. 
function lb_user_add() {
    $handler = $_SERVER['PHP_SELF'];
    // User type will add in future.
    $html = <<<END
    <div class="form">
    <h3>新建用户</h3>
        <form method="post" action="$handler" id="user_add_form">
            <table>
                <tr><td>登录名*：</td><td><input type="text" name="new_s_name" value=""/></td></tr>
                <tr><td>密码*：</td><td><input type="password" name="new_pswd_once" value=""/></td></tr>
                <tr><td>重复密码*：</td><td><input type="password" name="new_pswd_repeat" value=""/></td></tr>
                <tr><td>全名*：</td><td><input type="text" name="new_f_name" value=""/></td></tr>
                <tr><td>Email*：</td><td><input type="text" name="new_email" value=""/></td></tr>
                <tr><td colspan="2"><input type="submit" name="new_user_submit" value="创建用户"/></td></tr>
            </table>
        </form>
        <p class="footnote">带*的为必填项！</p>
    </div>
END;
    return $html;
}
function lb_password_change() {
    $handler = $_SERVER['PHP_SELF'];
    $html = <<<END
    <div class="form">
    <h3>修改密码</h3>
        <form method="post" action="$handler" id="pswd_change_form">
            <table>
                <tr><td>新密码*：</td><td><input type="password" name="change_pswd_once" value=""/></td></tr>
                <tr><td>重复新密码*：</td><td><input type="password" name="change_pswd_repeat" value=""/></td></tr>
                <tr><td colspan="2"><input type="submit" name="change_pswd_submit" value="修改"/></td></tr>
            </table>
        </form>
        <p class="footnote">带*的为必填项！</p>
    </div>
END;
    return $html;
}

function lb_userinfo_change() {
    $handler = $_SERVER['PHP_SELF'];
    // User type will add in future.
    $html = <<<END
    <div class="form">
    <h3>修改个人信息</h3>
        <form method="post" action="$handler" id="userinfo_change_form" name="userinfo_change_form">
            <table>
                <tr><td>全名：</td><td><input type="text" name="change_f_name" value=""/></td></tr>
                <tr><td>Email：</td><td><input type="text" name="change_email" value=""/></td></tr>
                <tr><td colspan="2"><input type="submit" name="change_userinfo_submit" value="修改"/></td></tr>
            </table>
        </form>
        <p class="footnote">至少填一项。</p>
    </div>
END;
    return $html;
}

// A navigation bar for administrators.
function lb_admin_navbar() {
    // Give Everyone the same admin link nav bar.
    // Wrapped in a <div>
    //$lb_url = lb_abs_url();
    $html = <<< END
    <div id="admin_navbar">
        <ul>
            <li><a href="lb_post.php">发表日志</a></li>
            <li><a href="lb_admin.php">管理首页</a></li>
            <li><a href="lb_users_admin.php">用户管理</a></li>
            <li><a href="lb_sessions_admin.php">直播管理</a></li>
            <li><a href="lb_posts_admin.php">消息管理</a></li>
            <li><a href="lb_sys_config.php">系统配置</a></li>
            <li><a href="../index.php">查看日志</a></li>
        </ul>
    </div>
END;
    return $html;    
}

function lb_welcome_barner() {
    $html = "<div class=\"welcome\">欢迎使用直播博客, " . $_COOKIE['author'] . "！</div>";
    $html .= lb_logout_form();
    return $html;
}

function lb_load_config($conf_name) {
    $query = "SELECT conf_value FROM lb_config WHERE conf_name='$conf_name'";
    $result = lb_db_query($query);
    if($result) {
        list($conf_value) = mysql_fetch_row($result);
        @mysql_close();
        return $conf_value;
    }
    else {
        @mysql_close();
        return false;
    }
}

?>
